﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SurfaceAd.Common;
using SurfaceAd.Entities.Ad;

/**
 * 创建时间：2014/9/24 15:03:34
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace SurfaceAd.Assistant
{
    internal sealed class AdResponseHelper
    {
        private const string DATAFLAG_START = ",\"data\":";
        private const string DATAFLAG_END_SUCCESS = "\"}}";
        private const string DATAFLAG_END_FAILURE = "\"}";

        public AdResponseHelper()
        {
        }

        private AdJson BuildAdJson(bool validity, string message, SurfaceAdStatus adStatus, AdResponse adResponse)
        {
            return new AdJson()
             {
                 Validity = validity,
                 Message = message,
                 StatusCode = adStatus,
                 AdContent = adResponse
             };
        }

        public AdJson ConvertToAdResponse(String adContent)
        {
            //{"code":200,"val":"","type":0,"data":{"w":"480","h":"80","img":"http:\/\/sadimg-vu-test.cloudapp.net\/image\/67f858f12df4009ede2ca157936d5816.png","url":"http:\/\/sadads-vu-test.cloudapp.net\/c.php?d=emlkPTE4JnR5cGU9MiZjaWQ9MTQmYWlkPTQ1JnVpZD0wMzAwN0NDNDA4MDBFQTY5MDUwMENFMTEwNjAwMDEwMDA0MDAzNjA4MDQwMEMzM0EwNDAwNTQ0QzA0MDBBQTk0MDEwMEU4OEMwMjAwRjRFRDA5MDA1MjZBJmhpZD04NDIwM2M1Yzk2NGI4MzZmM2FjMjZjNWM1NTAyZjRiNyZkPTEmdXJsPVl6RTBaVGt6WVdFdE1qZGtOeTFrWmpFeExXRTRORFF0TURBeU16ZGtaVEprWWpsbA==","jt":"market","jd":"c14e93aa-27d7-df11-a844-00237de2db9e"}}                        
            //{"code":400,"val":"","type":"","data":" Request UA is NULL ."}

            if (string.IsNullOrWhiteSpace(adContent))
            {
                return BuildAdJson(false, "广告数据为空！", SurfaceAdStatus.AdContent_Empty, null);
            }
            string endFlag = DATAFLAG_END_SUCCESS;
            if (adContent.EndsWith(DATAFLAG_END_FAILURE))
            {
                endFlag = DATAFLAG_END_FAILURE;
            }

            //将data对象转换为字符
            int startPosition = adContent.IndexOf(DATAFLAG_START);
            int endPosition = adContent.IndexOf(endFlag);
            if (startPosition < 0)
            {
                return BuildAdJson(false, "广告数据不完整！", SurfaceAdStatus.AdContent_Broken, null);
            }
            try
            {
                string dataContent = adContent.Substring(startPosition + DATAFLAG_START.Length, (endPosition - startPosition - DATAFLAG_START.Length) + (endFlag.Length - 1));
                string basicContent = adContent.Replace(dataContent, "\"\"");
                if (string.IsNullOrWhiteSpace(dataContent) || string.IsNullOrWhiteSpace(basicContent))
                {
                    return BuildAdJson(false, "广告数据丢失！", SurfaceAdStatus.AdContent_Losted, null);
                }
                //
                AdResponse adResponse = JSONHelper.Deserialize<AdResponse>(basicContent);
                adResponse.AdContentType = AdType.None;
                adResponse.AdContentJumpType = AdJumpType.None;
                if (adResponse == null)
                {
                    return BuildAdJson(false, "广告数据无法解析！", SurfaceAdStatus.AdContent_ParseError, null);
                }
                adResponse.Data = dataContent;
                //
                if (adResponse.Type.Equals(Convert.ToInt32(AdType.BannerImage).ToString()))
                {
                    adResponse.AdContentType = AdType.BannerImage;
                    adResponse.AdImage = JSONHelper.Deserialize<AdResponseImage>(dataContent);
                    if (adResponse.AdImage != null)
                    {
                        adResponse.AdContentJumpType = GetJumpType(adResponse.AdImage.JumpType);
                    }
                }
                else if (adResponse.Type.Equals(Convert.ToInt32(AdType.BannerVideo).ToString()))
                {
                    adResponse.AdContentType = AdType.BannerVideo;
                    adResponse.AdVideo = JSONHelper.Deserialize<AdResponseVideo>(dataContent);
                    if (adResponse.AdVideo != null)
                    {
                        adResponse.AdContentJumpType = GetJumpType(adResponse.AdVideo.JumpType);
                    }
                }
                else if (adResponse.Type.Equals(Convert.ToInt32(AdType.BannerText).ToString()))
                {
                    adResponse.AdContentType = AdType.BannerText;
                    adResponse.AdText = JSONHelper.Deserialize<AdResponseText>(dataContent);
                    if (adResponse.AdText != null)
                    {
                        adResponse.AdContentJumpType = GetJumpType(adResponse.AdText.JumpType);
                    }
                }
                else if (adResponse.Type.Equals(Convert.ToInt32(AdType.BannerRich).ToString()))
                {
                    adResponse.AdContentType = AdType.BannerRich;
                    adResponse.AdRich = JSONHelper.Deserialize<AdResponseRich>(dataContent);
                    if (adResponse.AdRich != null)
                    {
                        adResponse.AdContentJumpType = GetJumpType(adResponse.AdRich.JumpType);
                    }
                }
                else
                {
                    return BuildAdJson(false, dataContent, SurfaceAdStatus.AdContent_Type_NoExistence, null);
                }
                //处理正确
                return BuildAdJson(true, string.Empty, SurfaceAdStatus.AdContent_Ok, adResponse);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), "ConvertToAdResponse");
                return BuildAdJson(false, err.Message, SurfaceAdStatus.AdContent_Exception, null);
            }
        }

        /// <summary>
        /// 点击广告跳转类型
        /// </summary>
        /// <param name="jumpType"></param>
        /// <returns></returns>
        private AdJumpType GetJumpType(string jumpType)
        {
            AdJumpType adJumpType = AdJumpType.None;
            if (!string.IsNullOrWhiteSpace(jumpType))
            {
                jumpType = jumpType.ToLower().Trim();
                if (jumpType.Equals(AdJumpType.Call.ToString().ToLower().Trim()))
                {
                    adJumpType = AdJumpType.Call;
                }
                else if (jumpType.Equals(AdJumpType.Market.ToString().ToLower().Trim()))
                {
                    adJumpType = AdJumpType.Market;
                }
                else if (jumpType.Equals(AdJumpType.Browser.ToString().ToLower().Trim()))
                {
                    adJumpType = AdJumpType.Browser;
                }
            }
            return adJumpType;
        }

        /// <summary>
        /// 获取跳转地址
        /// </summary>
        /// <param name="adContent"></param>
        /// <returns></returns>
        public string GetJumpData(AdResponse adContent)
        {
            string jumpData = string.Empty;
            string result = string.Empty;
            //
            switch (adContent.AdContentType)
            {
                case AdType.BannerImage:
                    jumpData = adContent.AdImage.DestinationURL;
                    break;
                case AdType.BannerVideo:
                    jumpData = adContent.AdVideo.DestinationURL;
                    break;
                case AdType.BannerRich:
                    jumpData = adContent.AdRich.DestinationURL;
                    break;
                case AdType.BannerText:
                    jumpData = adContent.AdText.DestinationURL;
                    break;
            }
            //
            switch (adContent.AdContentJumpType)
            {
                case AdJumpType.Browser:
                case AdJumpType.Market:
                    result = jumpData;
                    break;
                case AdJumpType.Call:
                    string[] callInfo = jumpData.Split('|');
                    if (callInfo != null && callInfo.Length > 0)
                    {
                        if (callInfo.Length == 1)
                        {
                            //只有号码无显示名称
                            result = callInfo[0];
                        }
                        else if (callInfo.Length == 2)
                        {
                            //有号码和显示名称
                            result = callInfo[0];//显示名称暂时不使用(callInfo[1])
                        }
                    }
                    break;
            }
            //
            return result;
        }
    }
}
